using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Data.Common;
using System.Text.RegularExpressions;
using RelationTextBox;
using System.Configuration;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Threading;
using System.IO;

/// 14.02.2009 mai multe griduri rezumat si functia de gasire a gridului curent
/// 12.11.2008 s-a adaugat functia Grid_DataError care va fi apelata in cazul rezumatelor
///            prin adaugarea in constructor a liniei
///            conturiDGV.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(Grid_DataError);
/// 11.11.2008 adaugare proprietate pentru setari grid
///            initializarea inaltiimi liniilor din grid pe 20
/// 15.11.2008 adaugare functia de tiparire in toolbar            
/// 12.09.2009 adaugare functie virtuala apelabila in momentul schimbarii lunii curente    
/// 13.09.2009 adaugare proprietate de ReadOnly - macheta poate fi doar consultata
namespace ERPStudio
{
    public delegate void AfterAddHandler(object sender, DataGridViewCellEventArgs args);
    public delegate Boolean BeforeDelGridHandler(object sender, DataGridViewCellEventArgs args);
    public delegate Boolean BeforeDelHandler(object sender, EventArgs args);
    public delegate Boolean BeforeDelHandlerAfterMessage(object sender, EventArgs args,Boolean Detaliu);
    public delegate Boolean ValidatingAfterEndEditHandler(object sender);
    /// <summary>
    /// clasa de baza din care sunt derivate toate tipurile de forme
    /// folosite de aplicatie
    /// </summary>
    /// 

    public partial class StudioForm : Form
    {
        private Exception lastExceptions = null;
        public StudioForm(ModuleClass mInfo)
        {
            _moduleInfo = mInfo;
            InitializeComponent();
            this.KeyPreview = true;
            numeMacheta = Text;
            AcceptButton = null;
            if (ModuleInfo != null)
            {
                workConnString = mInfo.workConnectionString;
            }
                
        }
        /// <summary>
        /// lista machetelor care se inchid odata cu macheta curenta
        /// </summary>
        protected List<Form> _CloseFormList = new List<Form>();
        public StudioForm():this(null)
        {
            
        }


        protected List<ToolStripButton> _toolStripMainItems = new List<ToolStripButton>();

        private ModuleClass _moduleInfo = null;
        [Browsable(true)]
        [Description("Informatii despre modulul care ruleaza macheta")]
        [DefaultValue(true)]
        public ModuleClass ModuleInfo
        {
            get
            {
                return _moduleInfo;
            }
        }

        protected Boolean _AllowAddRow = true;
        [Browsable(true)]
        [Description("Activeaza butonul de adaugare cand este afisata macheta")]
        [DefaultValue(true)]
        public Boolean EnableMainAddButton
        {
            get
            {
                return _AllowAddRow;
            }
            set
            {
                _AllowAddRow = value;
                if (staticMdiParent != null)
                    staticMdiParent.AdaugaTSB.Enabled = _AllowAddRow;
            }
        }

        protected Boolean _DispalySaveStatus = true;
        [Browsable(true)]
        [Description("Afiseaza cate inregistratri s-au salvat")]
        [DefaultValue(true)]
        public Boolean DispalySaveStatus
        {
            get
            {
                return _DispalySaveStatus;
            }
            set
            {
                _DispalySaveStatus = value;
            }
        }


        private List<BindingSource> _listBndSourceMain = new List<BindingSource>();
        [Browsable(true)]
        [Description("Lista cu binding Source")]
        [DefaultValue(true)]
        public List<BindingSource> listBndSourceMain
        {
            get
            {
                return _listBndSourceMain;
            }
            set
            {
                _listBndSourceMain = value;
            }
        
        }

        private Boolean _AllowDelete = true;
        [Browsable(true)]
        [Description("Activeaza butonul de stergere cand este afisata macheta")]
        [DefaultValue(true)]
        public Boolean EnableMainDeleteButton
        {
            get
            {
                return _AllowDelete;
            }
            set
            {
                _AllowDelete = value;
                if (staticMdiParent != null)
                    staticMdiParent.StergeTSB.Enabled = _AllowDelete;
            
            }
        }

        private Boolean _AllowRezumat = true;
        [Browsable(true)]
        [Description("Activeaza butonul rezumat cand este afisata macheta")]
        [DefaultValue(true)]
        public Boolean EnableMainBrowseButton
        {
            get
            {
                return _AllowRezumat;
            }
            set 
            {
                _AllowRezumat = value;
                if (staticMdiParent!=null)
                    staticMdiParent.RezumatTSB.Enabled = _AllowRezumat;
            }
        }

        private Boolean _AllowSearch = true;
        [Browsable(true)]
        [Description("Activeaza butonul rezumat cand este afisata macheta")]
        [DefaultValue(true)]
        public Boolean EnableMainSearchButton
        {
            get
            {
                return _AllowSearch;
            }
            set
            {
                _AllowSearch = value;
                if (staticMdiParent != null)
                    staticMdiParent.CautaTSB.Enabled = _AllowSearch;
            }
        }

        protected Int32 _indexSaveButton = -1;
        private Boolean _localSaveButton = false;
        [Browsable(true)]
        [Description("Activeaza butonul salvare")]
        [DefaultValue(true)]
        public Boolean EnableLocalSaveButton
        {
            get
            {
                return _localSaveButton;
            }
            set
            {
                _localSaveButton = value;
                if (_localSaveButton)
                {
                    if (_indexSaveButton==-1)
                        _indexSaveButton = AddButton("Salvare[F9]", global::ERPStudio.Properties.Resources.salvare1, Salvare, ToolStripItemAlignment.Right, true);
                }
                else
                    if (_indexSaveButton != -1)
                    {
                        _toolStripMain.Items.Remove(listTSButton[_indexSaveButton]);
                        listTSButton.RemoveAt(_indexSaveButton);
                        _indexSaveButton = -1;
                    }
            }
        }

        public DataRowView currentRow = null;
        /// <summary>
        /// daca este setata pe true macheta poate fi doar consultata
        /// </summary>
        public Boolean ReadOnly = false;
        public Boolean EroareSalvare = false;
        /// <summary>
        /// randul selectat din grid la apasarea butonului de selectie
        /// </summary>
        public DataGridViewRow selectedRow = null;
        /// <summary>
        /// randul din tabela din dataset selectat
        /// </summary>
        public DataRowView selectedDataRow = null;
        /// <summary>
        /// index spre setul curent;
        /// </summary>
        private Int16 _IndexSetCurent=0;
        public Int16 IndexSetCurent
        {
            get { return _IndexSetCurent; }
            set { _IndexSetCurent = value; }
        }
        public String NumeUnitate = String.Empty;
        /// <summary>
        /// daca se poate cauta in macheta respectiva...
        /// </summary>
        public Boolean EnableSearch = true;
        public List<TextBox> lstPK = new List<TextBox>();
        public String numeMacheta = String.Empty;
        

        static public FrmMainMdi staticMdiParent = null;
        /// <summary>
        /// gridul care se va seta proprietatile comune
        /// si din care se selecteaza ceva
        /// </summary>
        public List<DataGridView> gridRezumat = new List<DataGridView>();
        /// <summary>
        /// conexiunea de lucru
        /// </summary>
        public String workConnString = null;

        protected int BSindexMaster = 0;
        protected int BSindexDetail = 1;
        /// <summary>
        /// lista butoanelor adaugate pe ToolStrip
        /// </summary>
        public List<ToolStripItem> listTSButton = new List<ToolStripItem>();
        public Int32 idxSelectedTSButton = -1; //no item selected
        /// <summary>
        /// Adaptorul cu care se lucreaza cu datele
        /// </summary>
        public List<SqlDataAdapter> listTableAdaptor = new List<SqlDataAdapter>();
        public Int32 NoRecAdded = 0;
        public Int32 NoRecUpdated = 0;
        /// <summary>
        /// id-ul din tabela de descriere a formelor
        /// </summary>
        public event EventHandler HandleAdd;
        public event EventHandler HandleBeforeAdd;
        public event AfterAddHandler HandleAfterAdd;
        public event EventHandler HandleMod;
        public event EventHandler HandleDel;
        public event BeforeDelHandler HandleBeforeDel;
        public event EventHandler HandleMoveFirst;
        public event EventHandler HandleMoveLast;
        public event EventHandler HandleMoveNext;
        public event EventHandler HandleMovePrev;
        public event EventHandler HandleAfterMove;
        public event EventHandler HandleBeforeSearch;
        public event EventHandler HandleSearch;
        public event EventHandler HandleRezumat;
        public event EventHandler HandleCard;
        public event EventHandler HandleSalvare;
        public event EventHandler HandleTiparire;
        public event EventHandler HandleF11;
        public event EventHandler HandleF12;
        
        /// <summary>
        /// Functia care se apeleaza in momentul apasarii butonului 
        /// de cautare
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="?"></param>
        virtual public void Cauta(object sender, EventArgs ev)
        {

            Trace.Assert(listBndSourceMain.Count > 0, "Nu s-a completata BindingSource!");
            if (!SalvareLocal()) return;
            if (listBndSourceMain.Count > 0)
            {
                SqlConnection conn = DeschideConexiune(workConnString);
                FrmSearch frmS = new FrmSearch(/*listDataTable[0],*/ listBndSourceMain[0],conn,ModuleInfo);
                frmS.ShowDialog();
                InchideConexiune(conn);
            }
            SetTitle();
        }

        /// <summary>
        /// seteaza titlul machetei
        /// </summary>
        public void SetTitle()
        {
            if (listBndSourceMain.Count == 0 || listBndSourceMain[0].Current == null)
                return;
            if (((DataRowView)listBndSourceMain[0].Current).IsNew)
            {
                Text = numeMacheta + " - Inregistrare noua";
                return;
            }
            if (lstPK.Count != 0)
            {
                Text = numeMacheta + " - ";
                foreach (TextBox tb in lstPK)
                    Text += tb.Text + ";";
            }

        }     

        public void SetStatus(string text)
        {
            this.toolStripStatusLabel1.Text = text;
        }

        virtual public void Adauga()
        {
            EventHandler tempBefore = HandleBeforeAdd;
            if (tempBefore != null)
                tempBefore(this, null);
            EventHandler temp = HandleAdd;
            if (temp != null)
                temp(this, null);
        }

        public void DupaAdauga(int RowIndex)
        {
            AfterAddHandler temp = HandleAfterAdd;
            DataGridViewCellEventArgs rand = new DataGridViewCellEventArgs(0,RowIndex);
            if (temp != null)
                temp(this, rand);
        }

        public void Modifica()
        {
            EventHandler temp = HandleMod;
            if (temp != null)
                temp(this, null);
        }

        public void Sterge()
        {
            Boolean dacaSterge = true;
            BeforeDelHandler tempb = HandleBeforeDel;
            if (tempb != null && EnableMainDeleteButton)
                dacaSterge = tempb(this, null);
            EventHandler  temp = HandleDel;
            if (temp != null && EnableMainDeleteButton && dacaSterge)
                temp(this, null);
        }

        public void FKey(Keys k)
        {
            if (k == Keys.F11)
            {
                EventHandler temp = HandleF11;
                if (temp != null)
                    temp(this, null);
            }
            if (k == Keys.F12)
            {
                EventHandler temp = HandleF12;
                if (temp != null)
                    temp(this, null);
            }
        }

        public void Cauta()
        {
            EventHandler tempBefore = HandleBeforeSearch;
            if (tempBefore != null)
                tempBefore(this, null);
            EventHandler temp = HandleSearch;
            if (temp != null && EnableSearch)
                temp(this, null);
        }
        public void Primul()
        {
            EventHandler temp = HandleMoveFirst;
            if (temp != null)
                temp(this, null);
            EventHandler tempM = HandleAfterMove;
            if (tempM != null)
                tempM(this, null);
        }
        public void Rezumat()
        {
            EventHandler temp = HandleRezumat;
            if (temp != null && EnableMainBrowseButton)
                temp(this, null);
        }
        public void Anterior()
        {
            EventHandler temp = HandleMovePrev;
            if (temp != null)
                temp(this, null);
            EventHandler tempM = HandleAfterMove;
            if (tempM != null)
                tempM(this, null);
        }
        public void Urmator()
        {
            EventHandler temp = HandleMoveNext;
            if (temp != null)
                temp(this, null);
            EventHandler tempM = HandleAfterMove;
            if (tempM != null)
                tempM(this, null);
        }
        public void Ultimul()
        {
            EventHandler temp = HandleMoveLast;
            if (temp != null)
                temp(this, null);
            EventHandler tempM = HandleAfterMove;
            if (tempM != null)
                tempM(this, null);
        }
        public void Card()
        {
            EventHandler temp = HandleCard;
            if (temp != null)
                temp(this, null);
        }

        public void Salvare()
        {
            EventHandler temp = HandleSalvare;
            if (temp != null)
                temp(this, null);
        }

        public void Tiparire()
        {
            EventHandler temp = HandleTiparire;
            if (temp != null)
                temp(this, null);
        }

        #region TrateazaExceptie
        public Boolean TrateazaExceptie(Exception ex)
        {
            return TrateazaExceptie(ex, 0);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="indVal">randul din binding source care va fi afisat</param>
        /// <returns></returns>
        public Boolean TrateazaExceptie(Exception ex, int indVal)
        {
            if (ex.Message == "DataGridViewComboBoxCell value is not valid.")
                return true;
            DataRowView ret = null;
            MessageBoxFrm mbt = new MessageBoxFrm("Selectie", ConvertErrMsg(ex, indVal, -1, String.Empty, out ret), "Renuntati la validari?",MessageBoxFrm.ImaginiMB.IntrebareIcon, ret);
            mbt.AddButton("Da", 70, mbt.MessageBoxFrm_Click_Yes);
            mbt.AddButton("Nu", 70, mbt.MessageBoxFrm_Click_No);
            DialogResult retD = mbt.ShowDialog();
            return retD == DialogResult.Yes;
            //MessageBox.Show(ConvertErrMsg(ex, indVal,-1,String.Empty)+ "\nRenuntati la validari?", "Eroare", MessageBoxButtons.YesNo, MessageBoxIcon.Stop)==DialogResult.Yes;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="rd">randul din grind in care e eroarea, daca e diferit de -1</param>
        /// <param name="col">coloana din grid in care e eroarea, daca e diferit de -1</param>
        /// <returns></returns>
        public Boolean TrateazaExceptie(Exception ex, int rd, String col)
        {
            if (ex.Message == "DataGridViewComboBoxCell value is not valid.")
                return true;
            DataRowView ret = null;
            //return MessageBox.Show(ConvertErrMsg(ex, -1,rd,col) + "\nRenuntati la validari?", "Eroare", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes;
            MessageBoxFrm mbt = new MessageBoxFrm("Eroare", ConvertErrMsg(ex, -1, rd, col, out ret), "Renuntati la validari?",MessageBoxFrm.ImaginiMB.IntrebareIcon, ret);
            mbt.AddButton("Da", 70, mbt.MessageBoxFrm_Click_Yes);
            mbt.AddButton("Nu", 70, mbt.MessageBoxFrm_Click_No);
            DialogResult retD = mbt.ShowDialog();
            return retD == DialogResult.Yes;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="indVal">indexul BS din tabela locala</param>
        /// <param name="rd"></param>
        /// <param name="col"></param>
        /// <returns></returns>
        public Boolean TrateazaExceptie(Exception ex, int indVal, int rd, String col)
        {
            if (ex.Message == "DataGridViewComboBoxCell value is not valid.")
                return true;
            DataRowView ret = null;
            //return MessageBox.Show(ConvertErrMsg(ex, indVal, rd, col) + "\nRenuntati la validari?", "Eroare", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes;
            MessageBoxFrm mbt = new MessageBoxFrm("Eroare", ConvertErrMsg(ex, indVal, rd, col, out ret), "Renuntati la validari?",MessageBoxFrm.ImaginiMB.IntrebareIcon, ret);
            mbt.AddButton("Da", 70, mbt.MessageBoxFrm_Click_Yes);
            mbt.AddButton("Nu", 70, mbt.MessageBoxFrm_Click_No);
            DialogResult retD = mbt.ShowDialog();
            return retD == DialogResult.Yes;

        }

        public Boolean TrateazaExceptie(Exception ex, Object indVal)
        {
            DataRowView ret = null;
            MessageBoxFrm mbt = new MessageBoxFrm("Selectie", ConvertErrMsg(ex, -1, -1, String.Empty, out ret), "Renuntati la validari?",MessageBoxFrm.ImaginiMB.IntrebareIcon, indVal);
            mbt.AddButton("Da", 70, mbt.MessageBoxFrm_Click_Yes);
            mbt.AddButton("Nu", 70, mbt.MessageBoxFrm_Click_No);
            DialogResult retD = mbt.ShowDialog();
            return retD == DialogResult.Yes;
            //MessageBox.Show(ConvertErrMsg(ex, indVal,-1,String.Empty)+ "\nRenuntati la validari?", "Eroare", MessageBoxButtons.YesNo, MessageBoxIcon.Stop)==DialogResult.Yes;
        }

        public static void ShowObject(Object indVal)
        {
            MessageBoxFrm mbt = new MessageBoxFrm("Show Object", "", "",MessageBoxFrm.ImaginiMB.InformareIcon, indVal);
            mbt.AddButton("Da", 70, mbt.MessageBoxFrm_Click_Yes);
            mbt.AddButton("Nu", 70, mbt.MessageBoxFrm_Click_No);
            DialogResult retD = mbt.ShowDialog();
            //return retD == DialogResult.Yes;
            //MessageBox.Show(ConvertErrMsg(ex, indVal,-1,String.Empty)+ "\nRenuntati la validari?", "Eroare", MessageBoxButtons.YesNo, MessageBoxIcon.Stop)==DialogResult.Yes;
        }

        #endregion

        public void MyTrace(String val)
        {
            Trace.WriteLine("[" + DateTime.Now.ToString() + "]" + val);
        }

        static public void MyStaticTrace(String val)
        {
            Trace.WriteLine("[" + DateTime.Now.ToString() + "]" + val);
        }
        /// <summary>
        /// returneaza numele campului aflat intre apostroafe
        /// </summary>
        /// <param name="errMsg"></param>
        /// <returns></returns>
        public String GetErrorFieldName(String errMsg)
        {
            String ret = String.Empty;
            Match m1 = Regex.Match(errMsg, @"\s*\w*'(?<field>[\w|\d|\\|\.|\-]+)'\s*\w*");
            if (m1.Success == true)
            {
                ret = m1.Groups["field"].ToString();
            }
            return ret;
        }
        /// <summary>
        /// Cauta controlul care are Bindingfields egal cu parametrul fn
        /// </summary>
        /// <param name="fn"></param>
        /// <param name="ccl"></param>
        /// <returns></returns>
        private Control SearchDMControl(String fn,String tabela, Control ccl)
        {
            if (ccl == null)
                return null;
            foreach (Control ctl in ccl.Controls)
            {
                Control rctl = SearchDMControl(fn, tabela,ctl);
                if (rctl != null)
                    return rctl;
                foreach (Binding cb in ctl.DataBindings)
                {
                    if (cb.BindingMemberInfo.BindingField == fn && ((BindingSource)cb.DataSource).DataMember==tabela)
                        return ctl;
                }
            }
            /// nu l-a gasit
            return null;        
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ex"></param>
        /// <param name="indVal">randul din binding source cu eroare daca e diferit de -1</param>
        /// <param name="rd">drandul din grid cu eroarea daca e diferit de -1</param>
        /// <param name="col">coloana cu eroarea daca e diferita de -1</param>
        /// <returns></returns>
        public String ConvertErrMsg(Exception ex,int indVal,int rd,String col,out DataRowView errRow)
        {
            errRow = null;
            // se afiseaza si randul la care apare problema
            String completare = String.Empty;
            if (this.listBndSourceMain.Count != 0 && indVal!=-1)
            {
                DataRowView dr = ((DataRowView)listBndSourceMain[indVal].Current);
                ///daca pe randul curent este eroarea
                if (dr!=null && dr.Row!=null)
                {
                    errRow = dr;
                    completare = "\n[";
                    foreach (object o in dr.Row.ItemArray)
                        completare += o.ToString() + ";";
                    completare += "]";
                }
            }

            if (rd != -1 && col != String.Empty)
            {
                completare = "\n(in coloana " + col + " din randul " + rd.ToString() + ")";
            }

            if (ex == null)
                return "Obiect exceptie = null!!!";
            String msg = String.Empty;
            msg = ex.Message;
            String errField = GetErrorFieldName(msg);
            Control ctl = SearchDMControl(errField, (indVal != -1 && listBndSourceMain.Count!=0) ? listBndSourceMain[indVal].DataMember : String.Empty, this);
            if (ex.GetType() == typeof(ConstraintException))
            {                
                msg = msg.Replace("Column", "Campul");
                msg = msg.Replace("is constrained to be unique", "contine doar valori unice");
                msg = msg.Replace("Value", "Valoare");
                msg = msg.Replace("is already present", "exista deja in aceasta coloana");
            }

            if (ex.GetType() == typeof(FormatException))
            {
                msg = msg.Replace("Column", "Campul");
                msg = msg.Replace("is constrained to be unique", "contine doar valori unice");
                msg = msg.Replace("Value", "Valoare");
                msg = msg.Replace("is already present", "exista deja in aceasta coloana");

            }

            if (ex.GetType() == typeof(ArgumentException))
            {
                msg = msg.Replace("Column", "Campul");
                msg = msg.Replace("value is not valid", "are o valoare incorecta");

            }

            if (ex.GetType() == typeof(NoNullAllowedException))
            {
                msg = msg.Replace("Column", "Campul");
                msg = msg.Replace("does not allow nulls", "nu poate avea valori nule");
            }
            if (ex.GetType() == typeof(InvalidOperationException))
            {

            }
            if (ex.GetType() == typeof(SqlException))
            {
                switch (((SqlException)ex).Number)
                {
                    case 207:
                        msg  = msg.Replace("Invalid column name", "Numele coloanei - incorect:");
                        break;
                    ///ex = {"The DELETE statement conflicted with the SAME TABLE REFERENCE constraint \"FK_Conturi_Conturi\". The conflict occurred in database \"ESRP\", table \"dbo.Conturi\".\r\nThe statement has been terminated."}
                    ///ex = {"The UPDATE statement conflicted with the CHECK constraint \"CK_Conturi_SI\". The conflict occurred in database \"ESRP\", table \"dbo.Conturi\".\r\nThe statement has been terminated."}
                    ///ex = {"The INSERT statement conflicted with the FOREIGN KEY constraint \"FK_ConturiCoresp_Conturi1\". The conflict occurred in database \"ESRP\", table \"dbo.Conturi\".\r\nThe statement has been terminated."}
                    ///base {System.Data.Common.DbException} = {"Cont neterminal in ContDebit,ContCredit\r\nThe transaction ended in the trigger. The batch has been aborted."}
                    ///
                    case 547:                        
                        msg = ex.Message;
                        Boolean seModifica = msg.Contains("UPDATE");
                        Boolean seSterge = msg.Contains("DELETE");
                        Boolean seAdauga = msg.Contains("INSERT");
                        msg = msg.Replace("The UPDATE statement conflicted with the", "Operatia de modificare este in conflict cu constrangerea");
                        msg = msg.Replace("The DELETE statement conflicted with the", "Operatia de stergere este in conflict cu constrangerea");
                        msg = msg.Replace("The INSERT statement conflicted with the", "Operatia de adaugare este in conflict cu constrangerea");
                        msg = msg.Replace("SAME TABLE REFERENCE constraint", "");
                        msg = msg.Replace("REFERENCE constraint","");
                        msg = msg.Replace("CHECK constraint", "de verificare");
                        msg = msg.Replace("FOREIGN KEY constraint", "de cheie externa");
                        msg = msg.Replace("The conflict occurred in database","Conflictul a aparut in baza de date");
                        msg = msg.Replace("table","tabela");
                        msg = msg.Replace("column","coloana");
                        msg = msg.Replace("The statement has been terminated","Operatia a fost anulata");
                        //msg = msg.Replace("column","coloana");

                        if(seSterge)
                            msg += "\nExplicatie suplimentara: \nInregistrarea care doreste sa se stearga este legata de inregistrarile din tabela specificata mai sus si nu poate fi eliminata!\nStergeti mai intai inregistrarile dependente si apoi reveniti!";
                        if(seModifica)
                            msg += "\nExplicatie suplimentara: \nInregistrarea se poate modifica respectand anumite reguli!\nUna din aceste reguli nu este respectata de catre valorile introduse de dumneavoastra!";
                        if (seAdauga)
                            msg += "\nExplicatie suplimentara: \nInregistrarea se poate adauga daca exista inregistrarile in tabela cu care se afla in relatie!\nAdaugati inregistrarile in tabela cu care este relationata inainte de a le adauga in tabela curenta!";

                        break;
                    case 229:
                        msg = "Nu aveti permisiunea sa accerati aceasta resursa!\n " + ex.Message;
                        break;
                    case 50000:
                        msg = msg.Replace("The transaction ended in the trigger", "\nTranzactia a fost incheiata in trigger.");
                        msg = msg.Replace("The batch has been aborted.", "Operatia a fost anulata");
                        break;
                }

            }
            if (ctl != null)
            {
                if (ctl.Parent!=null && ctl.Parent.GetType() == typeof(TabPage))
                {
                    TabControl tc = (TabControl)(ctl.Parent.Parent);
                    tc.SelectedTab = (TabPage)ctl.Parent;
                }
                ActiveControl = ctl;
            }
            //nu mai trimitem completare ca trimitem tot obiectulr
            //msg += completare;
            return msg;
        }

        public ToolStripComboBox AddComboBox(String nume, EventHandler funcButon, Object[] items, ToolStripItemAlignment align,int width)
        {
            ToolStripComboBox nCB = new ToolStripComboBox();
            if(items!=null && items.Length!=0)
                nCB.Items.AddRange(items);
            nCB.Alignment = align;
            nCB.Name = nume.Trim();
            nCB.Size = new System.Drawing.Size(width, 36);
            nCB.Text = nume;
            nCB.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
            if (funcButon!=null)
                nCB.Click += new System.EventHandler(funcButon);
            _toolStripMain.Items.Add(nCB);
            return nCB;
        }
     
        public void AddDropDown(String nume, Image img, EventHandler funcButon, ToolStripItem[] items,ToolStripItemAlignment align)
        {
            ToolStripSplitButton nBT = new ToolStripSplitButton();
            nBT.DropDownItems.AddRange(items);
            nBT.Alignment = align;
            nBT.Image = img;
            nBT.ImageTransparentColor = System.Drawing.Color.Magenta;
            nBT.Name = nume.Trim();
            nBT.Size = new System.Drawing.Size(71, 35);
            nBT.Text = nume;
            nBT.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
            if (funcButon!=null)
                nBT.DropDownClosed += new System.EventHandler(funcButon);
            _toolStripMain.Items.Add(nBT);
        }

        public void AddDropDownItem(String nume, EventHandler funcButon,ref List<ToolStripMenuItem> items)
        {
            ToolStripMenuItem itm = new ToolStripMenuItem();
            itm.Name = nume.Trim();
            itm.Size = new System.Drawing.Size(173, 22);
            itm.Text = nume;
            if(funcButon!=null)
                itm.Click += new System.EventHandler(funcButon);
            items.Add(itm);
        }
        /// <summary>
        /// adauga un nou buton pe bara de butoane
        /// </summary>
        /// <param name="nume"> numele butonului</param>
        /// <param name="img"> imaginea butonului</param>
        /// <param name="funcButon"> functia care se va apela la clic pe buton</param>
        public Int32 AddButton(String nume, Image img, EventHandler funcButon,ToolStripItemAlignment align,Boolean select)
        {
            listTSButton.Add(new ToolStripButton());
            Int32 index = listTSButton.Count - 1;

            listTSButton[index].Alignment = align;
            listTSButton[index].Image = img;
            listTSButton[index].ImageTransparentColor = System.Drawing.Color.White;
            listTSButton[index].Name = nume.Trim();
            listTSButton[index].Size = new System.Drawing.Size(38, 33);
            listTSButton[index].Text = nume;
            listTSButton[index].TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText;
            if (funcButon!=null)
                listTSButton[index].Click += new System.EventHandler(funcButon);
            if (select)
            {
                ///daca nu s-a selectat alt buton
                if (idxSelectedTSButton == -1)
                {
                    idxSelectedTSButton = index;
                    listTSButton[index].Select();
                }
            }
            _toolStripMain.Items.Add(listTSButton[index]);
            return index;
        }

        public ToolStripTextBox AddTextBox(String nume, ToolStripItemAlignment align, Int32 w)
        {
            ToolStripTextBox tsbox = new ToolStripTextBox();
            tsbox.Name = nume;
            tsbox.Size = new System.Drawing.Size(w, 36);
            tsbox.Alignment = align;
            Int32 index = _toolStripMain.Items.Add(tsbox);
            return tsbox;
        }

        public ToolStripProgressBar AddProgressBar(String nume, ToolStripItemAlignment align, Int32 w)
        {
            ToolStripProgressBar tsbox = new ToolStripProgressBar();
            tsbox.Name = nume;
            //tsbox.Size = new System.Drawing.Size(w, 20);
            tsbox.Alignment = align;
            tsbox.Width = w;
            Int32 index = _toolStripMain.Items.Add(tsbox);
            return tsbox;
        }

        public Int32 AddButton(String nume, Icon img, EventHandler funcButon, ToolStripItemAlignment align, Boolean select)
        {
            return AddButton(nume,img.ToBitmap(),funcButon,align,select);
        }

        public void EnableButton(Int32 idx,Boolean ena)
        {
            if (idx>=0 && idx < listTSButton.Count)
                listTSButton[idx].Enabled = ena;
        }

        public ToolStripLabel AddLabel(String nume, ToolStripItemAlignment align)
        {
            ToolStripLabel lab = new ToolStripLabel();
            listTSButton.Add(lab);
            lab.Alignment = align;
            lab.Name = nume;
            lab.Size = new System.Drawing.Size(138, 33);
            _toolStripMain.Items.Add(lab);
            return lab;

        }

        virtual public void InchideFrm(object sender, EventArgs e)
        {
            this.Close();
        }

        public static Boolean InchideConexiune(SqlConnection Conexiune)
        {
            if ((Conexiune == null))
            {
                return true;
            }
            try
            {
                Conexiune.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"Eroare");
                return false;
            }
            Conexiune.Dispose();
            return true ;

        }

        public void RemoveRowAdded(DataTable dt)
        { 
            foreach(DataRow  row in dt.Select("","", DataViewRowState.Added))
                dt.Rows.Remove(row);
        }
 
        public String GetNameDefaultUnit(String codUnit,SqlConnection conn)
        {
            Trace.Assert(conn!=null,"GetNameDefaultUnit - fara conexiune");
            String ret = String.Empty;
            SqlCommand cmd = new SqlCommand("SELECT [Denumire] FROm Unitati WHERE CodUnitate=" + codUnit, conn);
            Object dUni = cmd.ExecuteScalar();
            if (dUni != null && dUni != DBNull.Value)
                ret = dUni.ToString();
            return ret;
        
        }

        public static String GetConnectionString(String NumeParametru)
        {
            if (NumeParametru == null || NumeParametru == String.Empty)
            {
                MessageBox.Show("NumeParametru nu a fost definit pentru functia GetConnectionString()!!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return null;

            }
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");
            ConnectionStringSettings cs = config.ConnectionStrings.ConnectionStrings[NumeParametru];
            while ((cs == null) || (cs.ConnectionString == string.Empty))
            {
                FrmLogin frm = new FrmLogin();
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    cs = config.ConnectionStrings.ConnectionStrings[NumeParametru];
                }
                else
                    Application.Exit();
            }
            return cs.ConnectionString;
        }

        public static SqlConnection DeschideConexiuneFaraConfigurare(String NumeParametru)
        {
            if (NumeParametru == null || NumeParametru == String.Empty)
            {
                MessageBox.Show("NumeParametru nu a fost definit pentru functia DeschideConexiuneFaraConfigurare()!!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return null;

            }
            SqlConnection Conexiune = null;
            Conexiune = new SqlConnection();
            Cursor.Current = Cursors.WaitCursor;
            while (Conexiune.State != ConnectionState.Open)
            {
                try
                {
                    if (asynProc)
                        NumeParametru += ";Asynchronous Processing=true";
                    if (timeOut != -1)
                        NumeParametru = NumeParametru.Replace("Connection Timeout=15", "Connection Timeout=" + timeOut.ToString());
                    Conexiune.ConnectionString = NumeParametru;
                    Conexiune.InfoMessage += new SqlInfoMessageEventHandler(Conexiune_InfoMessage);
                    Application.DoEvents();

                    Conexiune.Open();
                }
                catch (Exception ex)
                {
                    Cursor.Current = Cursors.Default;
                    MyStaticTrace(NumeParametru + " " + ex.ToString());
                    //se trateaza eroare la nivelul urmator
                    //throw new Exception("Eroare in conectare la Baza de date folosind parametrii din " + NumeParametru + ".\n Modificati parametrii din meniul Autentificare!", ex);
                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare", NumeParametru + " " + ex.ToString(), String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, Conexiune);
                    mbt.AddButton("Iesire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                    throw ex;
                }
            }
            Cursor.Current = Cursors.Default;
            return Conexiune;
        }

        public static SqlConnection DeschideConexiune(String NumeParametru)
        {
            if (NumeParametru == null || NumeParametru == String.Empty)
            {
                MessageBox.Show("NumeParametru nu a fost definit pentru functia DeschideConexiune()!!", "Eroare", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return null;

            }
            SqlConnection Conexiune = null;
            System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");
            ConnectionStringSettings cs = config.ConnectionStrings.ConnectionStrings[NumeParametru];
            while ((cs == null) || (cs.ConnectionString == string.Empty))
            {
                FrmLogin frm = new FrmLogin();
                if (frm.ShowDialog() == DialogResult.OK)
                {
                    cs = config.ConnectionStrings.ConnectionStrings[NumeParametru];
                }
                else
                    Application.Exit();
            }
            Conexiune = new SqlConnection();
            Cursor.Current = Cursors.WaitCursor;
            while (Conexiune.State != ConnectionState.Open)
            {
                try
                {
                    if (asynProc)
                        cs.ConnectionString += ";Asynchronous Processing=true";
                    if (timeOut != -1)
                        cs.ConnectionString = cs.ConnectionString.Replace("Connection Timeout=15", "Connection Timeout=" + timeOut.ToString());
                    Conexiune.ConnectionString = cs.ConnectionString;
                    Conexiune.InfoMessage += new SqlInfoMessageEventHandler(Conexiune_InfoMessage);
                    Application.DoEvents();

                    Conexiune.Open();
                }
                catch (SqlException ex)
                {
                    Configuration configold = null, conCre = null;
                    try
                    {
                        // Get the application configuration file.OpenExeConfiguration*/
                        configold = ConfigurationManager.OpenExeConfiguration("ERPStudio.0.exe");
                    }
                    catch (ConfigurationErrorsException)
                    {

                        //conCre = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                        //if (conCre != null)
                        //    conCre.SaveAs("ERPStudio.0.exe.config");
                        //trebuie sa existe si fisierul .exe
                        FileStream sw = File.Create("ERPStudio.0.exe");
                        if (sw != null)
                            sw.Close();
                        configold = ConfigurationManager.OpenExeConfiguration("ERPStudio.0.exe");
                        // nu mai e nevoie de ele aducem altul...
                        File.Delete("ERPStudio.0.exe");
                    }

                    ConnectionStringSettings css = configold.ConnectionStrings.ConnectionStrings[NumeParametru];


                    ConfigurationSection sectionold = configold.GetSection("connectionStrings");
                    if (sectionold == null)
                    {
                        Trace.WriteLine("[" + DateTime.Now.ToString() + "] GetSection stringuri de conectare returnat null!");
                        Trace.Flush();
                        return null;
                    }

                    if (sectionold.SectionInformation.IsProtected)
                    {
                        try
                        {
                            sectionold.SectionInformation.UnprotectSection();
                            Trace.WriteLine("[" + DateTime.Now.ToString() + "] Deprotejare sectiune cripatata siruri de conectare!");
                        }
                        catch (Exception)
                        {
                            Trace.WriteLine("[" + DateTime.Now.ToString() + "] Eroare la deprotejare sectiune cripatata siruri de conectare!");
                        }
                    }

                    config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");


                    ConfigurationSection section = config.GetSection("connectionStrings");
                    if (section == null)
                    {
                        Trace.WriteLine("[" + DateTime.Now.ToString() + "] GetSection stringuri de conectare returnat null!");
                        Trace.Flush();
                        return null;
                    }

                    if (section.SectionInformation.IsProtected)
                    {
                        try
                        {
                            section.SectionInformation.UnprotectSection();
                            Trace.WriteLine("[" + DateTime.Now.ToString() + "] Deprotejare sectiune cripatata siruri de conectare!");
                        }
                        catch (Exception)
                        {
                            Trace.WriteLine("[" + DateTime.Now.ToString() + "] Eroare la deprotejare sectiune cripatata siruri de conectare!");
                        }
                    }


                    if (configold.ConnectionStrings.ConnectionStrings[NumeParametru] != null)
                    {
                        if (config.ConnectionStrings.ConnectionStrings[NumeParametru].ConnectionString != configold.ConnectionStrings.ConnectionStrings[NumeParametru].ConnectionString)
                        {

                            config.ConnectionStrings.ConnectionStrings[NumeParametru].ConnectionString = configold.ConnectionStrings.ConnectionStrings[NumeParametru].ConnectionString;


                            if (section != null && !section.SectionInformation.IsProtected)
                            {
                                section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
                            }

                            config.Save(ConfigurationSaveMode.Full);
                        }
                    }
                    switch(ex.Number)
                    {
                        case 18456:
                            //se trateaza eroare la nivelul urmator
                            //throw new Exception("Eroare in conectare la Baza de date folosind parametrii din " + NumeParametru + ".\n Modificati parametrii din meniul Autentificare!", ex);

                            //nu paraseste pana nu se conecteaza
                            ///deschide salvarea veche

                            FrmLogin frm = new FrmLogin();
                            frm.Text += ">>" + NumeParametru;
                            DialogResult ret = frm.ShowDialog();
                            if (ret == DialogResult.Cancel)
                            {
                                if (Application.AllowQuit)
                                {
                                    Application.Exit();
                                    return null;
                                }
                            }
                            //reciteste fisierul de configurare
                            config = ConfigurationManager.OpenExeConfiguration("ERPStudio.exe");
                            cs = config.ConnectionStrings.ConnectionStrings[NumeParametru];
                            break;
                        case 10051:
                            ///A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: TCP Provider, error: 0 - A socket operation was attempted to an unreachable network.)
                            ///A aparut o eroare legata de retea sau de instanta SQL. Nu a fost gasit serverul sau este inaccesibil. Verificati daca numele instantei este corect sau daca SQL-ul a fost configurat sa permita conectarea remote.(provider: TCP Provider, error: 0 - A socket operation was attempted to an unreachable network.)
                            MessageBoxFrm mbt = new MessageBoxFrm("Eroare", Properties.Resources.ResourceManager.GetString("SQLExceptionsConectionError"),String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, ex);
                            mbt.AddButton("Iesire", 70, mbt.MessageBoxFrm_Click_Yes);
                            if (mbt.ShowDialog() == DialogResult.Yes)
                                return null;
                            break;
                        default:
                            MessageBoxFrm mbt2 = new MessageBoxFrm("Eroare", ex.Message,String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, ex);
                            mbt2.AddButton("Oprire", 70, mbt2.MessageBoxFrm_Click_Yes);
                            mbt2.AddButton("Continua", 70, mbt2.MessageBoxFrm_Click_No);
                            if (mbt2.ShowDialog() == DialogResult.Yes)
                                return null;
                            break;
                    }
                }
                catch (Exception ex)
                {
                    Cursor.Current = Cursors.Default;
                    MyStaticTrace(cs.ConnectionString + " " + ex.ToString());
                    MessageBoxFrm mbt = new MessageBoxFrm("Eroare", cs.ConnectionString + " " + ex.ToString(), String.Empty, MessageBoxFrm.ImaginiMB.StopIcon, null);
                    mbt.AddButton("Iesire", 70, mbt.MessageBoxFrm_Click_Yes);
                    mbt.ShowDialog();
                    return null;
                }
            }
            Cursor.Current = Cursors.Default;
            SetUserHost(Conexiune);
            return Conexiune;

        }

        /// <summary>
        /// Deschide o conexiune cu un timeout specific
        /// </summary>
        /// <param name="NumeParametru"></param>
        /// <param name="timeout">timeout pe conexiune</param>
        /// <returns></returns>
        public static SqlConnection DeschideConexiune(String NumeParametru, Int16 timeout)
        {
            timeOut = timeout;
            return DeschideConexiune(NumeParametru);
        }

        public static SqlConnection DeschideConexiune(String NumeParametru, Boolean asincron)
        {
            asynProc = asincron;
            return DeschideConexiune(NumeParametru);
        }

        public static SqlConnection DeschideConexiune(String NumeParametru, Boolean asincron, Int16 timeout)
        {
            asynProc = asincron;
            timeOut = timeout;
            return DeschideConexiune(NumeParametru);
        }


        /// <summary>
        /// setat pentru procesare asincrona
        /// </summary>
        private static Boolean asynProc = false;
        private static Int16 timeOut = -1; 

        
        static void Conexiune_InfoMessage(object sender, SqlInfoMessageEventArgs e)
        {
            Application.DoEvents();
        }

        private void StudioForm_KeyUp(object sender, KeyEventArgs e)
        {
            switch(e.KeyCode)
            {
                case Keys.F2:
                    Rezumat();
                    break;
                case Keys.F3:
                    Adauga();
                    break;
                case Keys.F4:
                    Primul();
                    break;
                case Keys.F5:
                    Ultimul();
                    break;
                case Keys.F6:
                    Tiparire();
                    break;
                case Keys.F7:
                    Cauta();
                    break;
                case Keys.F8:
                    Sterge();
                    break;
                case Keys.F9:
                    Salvare();
                    break;
                case Keys.F10:
                    this.Close(); ;
                    break;
                case Keys.F11:
                    FKey(e.KeyCode);
                    break;
                case Keys.F12:
                    FKey(e.KeyCode);
                    break;

            }
        }
  
        public static object GetSetupValue(String table, String param,Int16 codUnit,SqlConnection wConn)
        {
            Trace.Assert(wConn != null, "Conexiunea trebuie sa fie alocata...");
            object ret = null;
            if (table == null || param == null || table == String.Empty || param == String.Empty)
            {
                MessageBox.Show("Functia GetSetupValue nu poate avea parametii nuli!", "Eroare programare");
                return ret;
            }
            SqlCommand comm = null;
            try
            {
                comm = new SqlCommand("SELECT [" + param + "] FROM [" + table + "] WHERE CodUnitate=" + codUnit.ToString(), wConn);
                ret = comm.ExecuteScalar();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                comm.Dispose();
            }
            return ret;

        }

        static public void SetArhiva(String anArhiva)
        {
            if (staticMdiParent != null)
                ((FrmMainMdi)staticMdiParent).SetArhiva(anArhiva);
        }

        static public Boolean EsteArhiva()
        {
            if (staticMdiParent != null)
            {
                return ((FrmMainMdi)staticMdiParent).EsteArhiva();
            }
            return false;
        }

        static public void SetUserHost(SqlConnection Conexiune)
        {
            if (Conexiune.State != ConnectionState.Open)
                return;
            SqlCommand cmd = new SqlCommand("SELECT system_user [User], host_name() [Host]", Conexiune);
            SqlDataReader rdr = cmd.ExecuteReader();
            if (rdr == null)
                return;
            rdr.Read();
            String user = rdr["User"].ToString();
            String host = rdr["Host"].ToString();
            rdr.Close();
            if (staticMdiParent!= null)
                ((FrmMainMdi)staticMdiParent).SetUserHost(user, host);
            cmd.Dispose();
        }

        /// <summary>
        /// functia apelata in caz de eroare in grid
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// 
        public void Grid_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            e.Cancel = true;
            #region Verificare validare celule grid si afisare mesaj exceptie
            if (e.Exception != null)
            {
                lastExceptions = e.Exception;
                SetStatus(e.Exception.Message);
            }
            else
            {
                lastExceptions = null;
                SetStatus(String.Empty);
            } 
            #endregion

            if ((sender!=null) && !((DataGridView)sender).Focused)
                return;
            DataGridView grid = (DataGridView)sender;
            String numeBS = String.Empty;
            if (grid != null)
            {
                if (grid.DataSource != null)
                {
                    BindingSource bs = (BindingSource)(grid.DataSource);
                    if (bs != null)
                        numeBS = bs.DataMember;
                }
            }
            ///cauta binding source in lista
            ///
            int BSidx = -1;
            if (numeBS != string.Empty)
            { 
                for(int i=0; i<listBndSourceMain.Count;i++)
                    if (listBndSourceMain[i].DataMember == numeBS)
                    {
                        BSidx = i;
                        break;
                    }
            }
            if (e.ColumnIndex!=-1)
            {
                if (e.ThrowException)
                {
                    if (TrateazaExceptie(e.Exception, BSidx, e.RowIndex, grid.Columns[e.ColumnIndex].HeaderText))
                    {
                        BindingSource bs = ((BindingSource)((DataGridView)sender).DataSource);
                        if (bs != null && bs.Current != null && ((DataRowView)bs.Current).Row.HasErrors)
                            bs.CancelEdit();
                    }
                }
            }
        }

        public void AddSource(BindingSource bs,SqlDataAdapter ta)
        {
            AddBindingSource(bs);
            AddTableAdaptor(ta);
            RegisterForLogTableAdaptor(ta);
        }

        public void AddSource(BindingSource bs, SqlDataAdapter ta, SqlCommand[] taCollection)
        {
            AddBindingSource(bs);
            AddTableAdaptor(ta);
            RegisterForLogTableAdaptor(taCollection);
        }


        public void AddBindingSource(BindingSource bs)
        {
            if (bs == null)
                throw new ArgumentNullException("BindingSource bs");
            bs.PositionChanged += new EventHandler(bs_PositionChanged);
            listBndSourceMain.Add(bs);
            
        }

        public void AddTableAdaptor(SqlDataAdapter ta)
        {
            if (ta == null)
                throw new ArgumentNullException("SqlDataAdapter ta");
            listTableAdaptor.Add(ta);
        }

        /// <summary>
        /// inregistreaza adaptorul pentru a genera informatii de log
        /// </summary>
        /// <param name="ta"></param>
        public void RegisterForLogTableAdaptor(SqlDataAdapter ta)
        {
            if (ta == null)
                throw new ArgumentNullException("SqlDataAdapter ta");
            ta.FillError += Command_StatementError;
            if (ta.SelectCommand != null)
            {
                ta.SelectCommand.StatementCompleted += Command_StatementCompleted;
            }
            if (ta.InsertCommand != null)
                ta.InsertCommand.StatementCompleted += Command_StatementCompleted;
            if (ta.UpdateCommand != null)
                ta.UpdateCommand.StatementCompleted += Command_StatementCompleted;
            if (ta.DeleteCommand != null)
                ta.DeleteCommand.StatementCompleted += Command_StatementCompleted;
            
        }

        public void RegisterForLogTableAdaptor(SqlCommand[] taCollection)
        {
            if (taCollection == null)
                throw new ArgumentNullException("RegisterForLogTableAdaptor null");

            foreach (SqlCommand ta in taCollection)
            {
                ta.StatementCompleted += Command_StatementCompleted;
            }
        }

        public void Command_StatementCompleted(object sender, StatementCompletedEventArgs e)
        {
            SqlCommand cmd = sender as SqlCommand,spCmd = new SqlCommand("write_log");
            spCmd.CommandType = CommandType.StoredProcedure;
            Boolean dbConn = false;
            spCmd.Connection = DeschideConexiune(workConnString);
            dbConn = true;
            

            if (spCmd.Connection.State != ConnectionState.Open)
                spCmd.Connection.Open();
            String sqlParam = String.Empty;
            foreach(SqlParameter  par in cmd.Parameters)
            {
                sqlParam += par.ParameterName + "=" + par.Value.ToString() + ";";
            }
            String saveCmd = cmd.CommandText.Substring(0,Math.Min(8000,cmd.CommandText.Length));
            saveCmd= saveCmd.Replace("'", "''");
            saveCmd = saveCmd.Replace("\n", " ");
            saveCmd = saveCmd.Replace("\t", " ");
            saveCmd = saveCmd.Replace("     ", " ");
            saveCmd = saveCmd.Replace("    ", " ");
            saveCmd =saveCmd.Replace("   ", " ");
            saveCmd = saveCmd.Replace("  ", " ");
            spCmd.Parameters.Add(new SqlParameter("SqlCommand", saveCmd));
            spCmd.Parameters.Add(new SqlParameter("SqlParam", sqlParam.Substring(0, Math.Min(8000, sqlParam.Length))));
            spCmd.Parameters.Add(new SqlParameter("ErrMessage", "Ok"));
            spCmd.Parameters.Add(new SqlParameter("idLog", 0));
            spCmd.Parameters["idLog"].Direction = ParameterDirection.Output;

            try
            {
                spCmd.ExecuteNonQuery();
            }
            catch(Exception ex)
            {
                MyTrace(ex.Message);
            }

            if (dbConn)
                InchideConexiune(spCmd.Connection);
        }

        public void Command_StatementError(object sender, FillErrorEventArgs e)
        {
            SqlCommand cmd = sender as SqlCommand, spCmd = new SqlCommand("write_log");
            spCmd.CommandType = CommandType.StoredProcedure;
            Boolean dbConn = false;
            spCmd.Connection = DeschideConexiune(workConnString);
            dbConn = true;


            if (spCmd.Connection.State != ConnectionState.Open)
                spCmd.Connection.Open();
            String sqlParam = String.Empty;
            foreach (SqlParameter par in cmd.Parameters)
            {
                sqlParam += par.ParameterName + "=" + par.Value.ToString() + ";";
            }
            String saveCmd = cmd.CommandText.Substring(0, Math.Min(8000, cmd.CommandText.Length));
            saveCmd = saveCmd.Replace("'", "''");
            saveCmd = saveCmd.Replace("\n", " ");
            saveCmd = saveCmd.Replace("\t", " ");
            saveCmd = saveCmd.Replace("     ", " ");
            saveCmd = saveCmd.Replace("    ", " ");
            saveCmd = saveCmd.Replace("   ", " ");
            saveCmd = saveCmd.Replace("  ", " ");
            spCmd.Parameters.Add(new SqlParameter("SqlCommand", saveCmd));
            spCmd.Parameters.Add(new SqlParameter("SqlParam", sqlParam.Substring(0, Math.Min(8000, sqlParam.Length))));
            spCmd.Parameters.Add(new SqlParameter("ErrMessage", ""));
            spCmd.Parameters.Add(new SqlParameter("idLog", 0));
            spCmd.Parameters["idLog"].Direction = ParameterDirection.Output;

            try
            {
                spCmd.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MyTrace(ex.Message);
            }

            if (dbConn)
                InchideConexiune(spCmd.Connection);
        }

        void bs_PositionChanged(object sender, EventArgs e)
        {
            BindingSource bs = sender as BindingSource;
            DataRowView drv = ((DataRowView)bs.Current);
            String stare = String.Empty;
            if(drv!=null)
            {
                if(drv.IsEdit)
                    stare = "EDIT";
                if(drv.IsNew)
                    stare = "NEW";

            }

            StatusRecordNumber.Text = String.Format("{0} din {1}|{2}", bs.Position+1, bs.Count,stare);
        }

        private void StudioForm_Load(object sender, EventArgs e)
        {
            StartPosition = FormStartPosition.CenterScreen;
            FormatAllGrids(this);
            if (MdiParent != null && staticMdiParent==null)
                staticMdiParent = MdiParent as FrmMainMdi;
            if (gridRezumat.Count == 0)
                return;

            

            foreach (DataGridView _gridRezumat in gridRezumat)
            {
                System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
                System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();

                dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
                dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Window;
                dataGridViewCellStyle1.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText;
                dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.Highlight;
                dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
                dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
                _gridRezumat.ColumnHeadersDefaultCellStyle = dataGridViewCellStyle1;

                dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
                dataGridViewCellStyle2.BackColor = System.Drawing.SystemColors.Window;
                dataGridViewCellStyle2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                dataGridViewCellStyle2.ForeColor = System.Drawing.SystemColors.WindowText;
                dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.Highlight;
                dataGridViewCellStyle2.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
                dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
                _gridRezumat.RowHeadersDefaultCellStyle = dataGridViewCellStyle2;

                _gridRezumat.BackgroundColor = System.Drawing.SystemColors.Window;
                _gridRezumat.RowTemplate.Height = 20;
                _gridRezumat.RowHeadersWidth = 25;
                _gridRezumat.EditMode = DataGridViewEditMode.EditOnEnter;
                //_gridRezumat.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
                _gridRezumat.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                ///formateaza coloanele
                foreach (DataGridViewColumn dc in _gridRezumat.Columns)
                {
                    if (dc.ReadOnly || _gridRezumat.ReadOnly)
                        dc.DefaultCellStyle.BackColor = Color.LightGray;
                }
                _gridRezumat.EnableHeadersVisualStyles = false;
                //_gridRezumat.MultiSelect = false;
                _gridRezumat.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.Single;
                _gridRezumat.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(Grid_DataError);  
            }
            
        }

        public void InitAdapter(SqlDataAdapter ta,SqlConnection sqlConn,SqlTransaction tra)
        {

            if (ta.SelectCommand != null)
            {

                if (ta.SelectCommand.Connection == null)
                {
                    ta.SelectCommand.Connection = sqlConn;
                }
                if (tra != null)
                    ta.SelectCommand.Transaction = tra;
            }

            if ((ta.UpdateCommand!=null) && (ta.UpdateCommand.Connection == null || ta.UpdateCommand.Connection.State != ConnectionState.Open))
            {
                ta.UpdateCommand.Connection = sqlConn;
            }
            if (tra != null)
                ta.UpdateCommand.Transaction = tra;

            if ((ta.InsertCommand!=null) && (ta.InsertCommand.Connection == null || ta.InsertCommand.Connection.State != ConnectionState.Open))
            {
                ta.InsertCommand.Connection = sqlConn;
            }
            if (tra != null)
                ta.InsertCommand.Transaction = tra;

            if ((ta.DeleteCommand!= null) && (ta.DeleteCommand.Connection == null || ta.DeleteCommand.Connection.State != ConnectionState.Open))
            {
                ta.DeleteCommand.Connection = sqlConn;
            }
            if (tra != null)
                ta.DeleteCommand.Transaction = tra;

        }
        /// <summary>
        /// Seteaza informatia din luna,an
        /// </summary>
        /// <param name="text"></param>
        public void SetInfoLunaAnul(String text)
        {
            toolStripLabelAnLuna.Text = text;
            if (ModuleInfo.CurrentTheme == "tribunal")
            {
                toolStripLabelAnLuna.Alignment = ToolStripItemAlignment.Right;
                toolStripLabelAnLuna.Visible = false;
                IesireTSB.Alignment = ToolStripItemAlignment.Right;
            }
        }

        private void StudioForm_HelpRequested(object sender, HelpEventArgs hlpevent)
        {

        }

        /// <summary>
        /// returneaza indexul gridului selectat 
        /// </summary>
        /// <returns></returns>
        public Int16 GetCurrentGrid()
        {
            if (gridRezumat.Count == 0)
                return -1;
            foreach (DataGridView gdv in gridRezumat)
            {
                if (gdv.Visible && (gdv.ContainsFocus || gdv.Focused))
                    return (short)gridRezumat.IndexOf(gdv);
                
            }
            //daca nu are nimeni focusul returneaza primul grid
            return 0;
        }

        #region Functii Virtuale

        virtual public void SetCurentUnit(short codUnitate)
        {
            throw new NotImplementedException();
        }

        virtual public void SetCurentUnit(short codUnitate,SqlConnection con)
        {
            SetCurentUnit(codUnitate);
        }

        /// <summary>
        /// apelata in momentul schimbarii lunii curente
        /// </summary>
        /// <param name="codUnitate"></param>
        virtual public void SetCurentMonth(short codUnitate)
        {
            throw new NotImplementedException();
        }

        virtual public void toolStripLabelAnLuna_Click(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }
        #endregion

       
        /// <summary>
        /// Functia apelata pentru salvarea locala a datelor
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        /// 
        public Boolean SalvareLocal()
        {
            int indVal = 0;
            try
            {
                if (!Validate())
                    return false;
                foreach (BindingSource bs in listBndSourceMain)
                {
                    if (bs.Current != null)
                    {
                        DataRowState drv = ((DataRowView)bs.Current).Row.RowState;

                        if (drv != DataRowState.Unchanged)
                            bs.EndEdit();
                    }
                    indVal++;
                }
            }
            catch (Exception ex)
            {
                TrateazaExceptie(ex, indVal);
                return false;
            }
            return true;
        }
        /// <summary>
        /// returneaza valoarea setarii locale pentru utilizatorul curent din baza de date
        /// </summary>
        /// <param name="con">Conexiunea</param>
        /// <param name="nume">Numele setarii</param>
        /// <param name="defaultValue">Valoarea implicita returnata daca nu se gaseste nimic in baza de date</param>
        /// <param name="codUnit">Codul unitatii de pe care se verifica</param>
        /// <returns>Valoarea setarii ca string</returns>
        public String GetSetariLocale(SqlConnection con, String nume,String defaultValue,Int16 codUnit)
        {
            SqlCommand cmd = new SqlCommand("", con);
            Object retObj = null;
            cmd.CommandText = "SELECT [valoare] FROM [SetariLocale] WHERE [xUser] = system_user AND [xHost]=host_name() AND [CodUnitate]="+codUnit.ToString()+" AND [CodSetare]='" + nume + "'";
            retObj = cmd.ExecuteScalar();
            if (retObj == null || retObj == DBNull.Value)
            {
                //daca nu exista inregistrare se adauga una...
                cmd.CommandText = "INSERT  INTO [SetariLocale] ([xUser],[xHost],[CodSetare],[CodUnitate],[Valoare]) VALUES(system_user,host_name(),'" + nume + "',"+codUnit.ToString()+",'" + defaultValue + "')";
                cmd.ExecuteScalar();
                cmd.CommandText = "SELECT [valoare] FROM [SetariLocale] WHERE [xUser] = system_user AND [xHost]=host_name() AND [CodSetare]='"+nume+"' AND [CodUnitate]="+codUnit.ToString() ;
                retObj = cmd.ExecuteScalar();
            }
            if (retObj != null && retObj != DBNull.Value)
                return retObj.ToString();
            
            return String.Empty;
        }
        /// <summary>
        /// returneaza valoarea setarii locale pentru utilizatorul curent al aplicatiei
        /// </summary>
        /// <param name="con">Conexiunea</param>
        /// <param name="nume">Numele setarii</param>
        /// <param name="defaultValue">Valoarea implicita returnata daca nu se gaseste nimic in baza de date</param>
        /// <param name="codUnit">Codul unitatii de pe care se verifica</param>
        /// <param name="utilizator">Utilizatorul pentru care se returneaza setarea</param>
        /// <returns>Valoarea setarii ca string</returns>
        public String GetSetariLocale(SqlConnection con, String nume, String defaultValue, Int16 codUnit, Guid utilizator)
        {
            SqlCommand cmd = new SqlCommand("", con);
            Object retObj = null;
            cmd.CommandText = "SELECT [valoare] FROM [SetariLocale] WHERE [xUser] = system_user AND [xHost]=host_name() AND [CodUnitate]=" + codUnit.ToString() + " AND [CodSetare]='" + nume + "' AND [UserId]='" +
                utilizator.ToString() + "'";
            retObj = cmd.ExecuteScalar();
            if (retObj == null || retObj == DBNull.Value)
            {
                //daca nu exista inregistrare se adauga una...
                cmd.CommandText = "INSERT  INTO [SetariLocale] ([xUser],[xHost],[CodSetare],[CodUnitate],[Valoare],[UserId]) VALUES(system_user,host_name(),'" + nume + "'," + codUnit.ToString() + ",'" + defaultValue + "','"+utilizator.ToString()+"')";
                cmd.ExecuteScalar();
                cmd.CommandText = "SELECT [valoare] FROM [SetariLocale] WHERE [xUser] = system_user AND [xHost]=host_name() AND [CodSetare]='" + nume + "' AND [CodUnitate]=" + codUnit.ToString() + " AND [UserId]='" +
                utilizator.ToString() + "'";
                retObj = cmd.ExecuteScalar();
            }
            if (retObj != null && retObj != DBNull.Value)
                return retObj.ToString();

            return String.Empty;
        }

        public void SetSetariLocale(SqlConnection con, String nume, String Value,Int16 codUnit)
        {
            SqlCommand cmd = new SqlCommand("", con);
            Object retObj = null;
            cmd.CommandText = "UPDATE [SetariLocale] SET [Valoare]='" + Value + "' WHERE [xUser] = system_user AND [xHost]=host_name() AND [CodUnitate]=" + codUnit.ToString() + " AND [CodSetare]='" + nume + "' AND [CodUnitate]=" + codUnit.ToString();
            try
            {
                retObj = cmd.ExecuteScalar();
            }
            catch(Exception)
            {
                cmd.CommandText = "INSERT  INTO [SetariLocale] ([xUser],[xHost],[CodSetare],[CodUnitate],[Valoare]) VALUES(system_user,host_name(),'" + nume + "',"+codUnit.ToString()+"," + Value + ")";
                cmd.ExecuteScalar();
            }
        }
        /// <summary>
        /// Seteaza o valoare pentru o setare locala pentru un anumit utilizator
        /// </summary>
        /// <param name="con"></param>
        /// <param name="nume"></param>
        /// <param name="Value"></param>
        /// <param name="codUnit"></param>
        /// <param name="utilizator"></param>
        public void SetSetariLocale(SqlConnection con, String nume, String Value, Int16 codUnit,Guid utilizator)
        {
            SqlCommand cmd = new SqlCommand("", con);
            Object retObj = null;
            cmd.CommandText = "UPDATE [SetariLocale] SET [Valoare]='" + Value + "' WHERE [xUser] = system_user AND [xHost]=host_name() AND [CodUnitate]=" + codUnit.ToString() + " AND [CodSetare]='" + nume + "' AND [CodUnitate]=" + codUnit.ToString() + " AND [UserId]='" +
                utilizator.ToString() + "'"; 
            try
            {
                retObj = cmd.ExecuteScalar();
            }
            catch (Exception)
            {
                cmd.CommandText = "INSERT  INTO [SetariLocale] ([xUser],[xHost],[CodSetare],[CodUnitate],[Valoare],[UserId]) VALUES(system_user,host_name(),'" + nume + "'," + codUnit.ToString() + "," + Value +",'" + utilizator.ToString() + "')";
                cmd.ExecuteScalar();
            }
        }

        protected override bool ProcessDialogKey(Keys keyData)
        {
            bool ret = base.ProcessDialogKey(keyData);
            return ret;
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if ((keyData == Keys.Return)) 
            {
                if ((this.ActiveControl.GetType() == typeof(ToolStrip)))
                { 
                    //daca este tul strip, enter da click pe butonul curent
                    ToolStrip curCtrl = this.ActiveControl as ToolStrip;
                    if ((idxSelectedTSButton != -1) && (idxSelectedTSButton < listTSButton.Count))
                    {
                        listTSButton[idxSelectedTSButton].PerformClick();
                    }
                    else
                    {
                        foreach (ToolStripItem itm in curCtrl.Items)
                        {
                            if (itm.Selected && itm.GetType() == typeof(ToolStripButton))
                            {
                                itm.PerformClick();
                                break;
                            }

                        }
                    }
                    return true; 

                }
                SendKeys.Send("{TAB}");
                return true; 
            } 
            else 
            { 
                return base.ProcessCmdKey(ref msg, keyData); 
            }
        }

        /// <summary>
        /// Cauta printre controalele din grid si le formateaza
        /// </summary>
        private void FormatAllGrids(Control ccl)
        {
            if (ccl == null)
                return;
            foreach (Control ctl in ccl.Controls)
            {
                ///verifica daca e grid
                if (ctl.GetType() == typeof(DataGridView) || ctl.GetType() == typeof(DataGridview))
                {
                    gridRezumat.Add((DataGridView)ctl);
                }
                ///prelucreaza controlele incluse
                FormatAllGrids(ctl);

            }
        }

        virtual public void Salvare(object sender, EventArgs args)
        {
            throw new NotImplementedException();           
        }

        protected DataTable GetDataTable(int idxCurent)
        {
            if (idxCurent >= listBndSourceMain.Count || listBndSourceMain[idxCurent].DataSource==null)
                return null;
            DataSet _localDS = listBndSourceMain[idxCurent].DataSource as DataSet;
            BindingSource _localBS = null;
            String _localTableName = listBndSourceMain[idxCurent].DataMember;
            DataTable _localDT = null;
            if (listBndSourceMain[idxCurent].DataSource.GetType() == typeof(BindingSource))
            {
                _localBS = listBndSourceMain[idxCurent].DataSource as BindingSource;
                _localDS = _localBS.DataSource as DataSet;
                if (_localBS.DataSource.GetType() == typeof(BindingSource))
                {
                    _localBS = _localBS.DataSource as BindingSource;
                    _localDS = _localBS.DataSource as DataSet;
                }
                _localDT = _localDS.Relations[_localTableName].ChildTable;
            }
            else
                _localDT = _localDS.Tables[_localTableName];
            return _localDT;
        }
        /// <summary>
        /// Metoda ruleaza o clasa din alt modul
        /// </summary>
        /// <param name="modul">numele modulului</param>
        /// <param name="numeClasa">numele clasei</param>
        /// <param name="param">parametrii transmisi constructorului</param>
        /// <returns></returns>
        public Object RuleazaFrm(String modul,String numeClasa, Object[] param,out Type mModule)
        {
            Object newFrm = null;
            FrmMainMdi frm = MdiParent as FrmMainMdi;
            if (Application.OpenForms["FrmMainMdi"] != null)
                frm = Application.OpenForms["FrmMainMdi"] as FrmMainMdi;

            Assembly asm = frm.GetModule(modul.ToLower());
            mModule = asm.GetType(numeClasa);
            if (mModule != null)
            {
                newFrm = asm.CreateInstance(numeClasa, true, BindingFlags.Public | BindingFlags.Instance | BindingFlags.CreateInstance, null,
                    param, Thread.CurrentThread.CurrentCulture, new object[] { });
            }
            return newFrm;
            
        }

        public void SetCurrentDataSource(BindingSource s)
        {
            if (listBndSourceMain.Contains(s))
                _IndexSetCurent = (short)listBndSourceMain.FindIndex(delegate(BindingSource bk) {return bk == s;});
        }

        public void EnableProgressBar(int min, int max)
        {
            toolStripProgressBar.Visible = true;
            toolStripProgressBar.Maximum = max;
            toolStripProgressBar.Minimum = min;
        }

        public void DisableProgressBar()
        {
            toolStripProgressBar.Visible = false;
        }

        public void SetProgressBar(int val)
        {
            toolStripProgressBar.Value = val ;
        }

        public DataTable GetDatabaseColumsInformation(SqlConnection con)
        {
            if (con.State != ConnectionState.Open)
                return null;
            SqlCommand cmd = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.COLUMNS ORDER BY TABLE_NAME ASC", con);
            SqlDataReader dr = cmd.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Load(dr);
            return dt;
        }


    }
}